﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    internal class TcpIpServer
    {
        private TcpListener tcpListener;
        private TcpClient connectedClient;
        private Thread listenerThread;
        private NetworkStream clientStream;
        private Action<string> logAction;
        public event Action<string> DataReceived;


        public TcpIpServer(Action<string> logAction)
        {

            //this.logAction = logAction;
            this.logAction = logAction ?? throw new ArgumentNullException(nameof(logAction), "Log action cannot be null");
        }
        public bool Connect(string ipAddress, int port) 
        {
            try
            {
                tcpListener = new TcpListener(IPAddress.Parse(ipAddress), port);
                tcpListener.Start();
                
                listenerThread = new Thread(new ThreadStart(ListenForClients));
                listenerThread.Start();
                Log("TCP Server started.");
                return true;

            }
            catch (SocketException ex)
            {
                Log($"SocketException: {ex.Message}");
                
                return false;
            }
            catch (Exception ex)
            {
                Log($"Exception: {ex.Message}");
                return false;
            }

        }

        private void ListenForClients()
        {
            try
            {
                connectedClient = tcpListener.AcceptTcpClient();
                clientStream = connectedClient.GetStream();
                Log("Client connected.");
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(connectedClient);
            }
            catch (Exception ex)
            {
                Log($"Exception in ListenForClients: {ex.Message}");
            }
        }

        private void HandleClientComm(object client_obj)
        {
            TcpClient tcpClient = (TcpClient)client_obj;
            NetworkStream stream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    bytesRead = stream.Read(message, 0, 4096);
                }
                catch
                {
                    break;
                }

                if (bytesRead == 0)
                    break;

                string receivedData = Encoding.ASCII.GetString(message, 0, bytesRead);
                Log($"Data received: {receivedData}");

                // 触发 DataReceived 事件，将接收到的数据传递出去
                DataReceived?.Invoke(receivedData);
            }

            tcpClient.Close();
        }

        public void Send(string data)
        {
            if (clientStream != null && connectedClient.Connected)
            {
                byte[] dataBytes = Encoding.ASCII.GetBytes(data);
                clientStream.Write(dataBytes, 0, dataBytes.Length);
                Log($"Data sent: {data}");
            }
            else
            {
                Log("No client connected.");
            }
        }

        public void Stop()
        {
            tcpListener.Stop();
            listenerThread.Abort();
            Log("TCP Server stopped.");
        }

        private void Log(string message)
        {
            logAction?.Invoke(message);
        }
    }
}
